/*
 * Copyright (C) 2013 Michael
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.jm.jmsql.database;

import com.jm.commons.logging.LogSystem;
import com.jm.commons.ui.UIBounds;
import com.jm.jmsql.JMSql;
import com.jm.jmsql.models.JMSqlObjectTableModel;
import com.jm.jmsql.objects.Column;
import com.jm.jmsql.objects.Database;
import com.jm.jmsql.objects.Databases;
import com.jm.jmsql.objects.Definition;
import com.jm.jmsql.objects.Schema;
import com.jm.jmsql.objects.Table;
import com.jm.jmsql.objects.Tables;
import com.jm.jmsql.sql.SQLEditor;
import com.jm.jmsql.sql.ViewSQLStructure;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @created Feb 27, 2013
 * @author Michael L.R. Marques
 */
public class CreateTable extends javax.swing.JDialog {
    
    /**
     * 
     */
    private JMSql app;
    
    /**
     * 
     */
    private Tables tables;
    
    /**
     * Creates new form CreateTable
     * 
     * @param app
     * @param tables 
     */
    public CreateTable(JMSql app, Tables tables) {
        super(app);
        initComponents();
        UIBounds.setBounds(app, this);
        //
        this.mainPanel.setImage(new java.io.File("./images/optionslogo.png"));
        // Set the icon image
        try {
            setIconImage(ImageIO.read(getClass().getClassLoader().getResource("com/jm/jmsql/icons/create_table.png")));
        } catch (IOException ioe) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Set the icon image", ioe);
        }
        this.app = app;
        this.tables = tables;
        // Create an empty table model
        this.tableColumns.setModel(new JMSqlObjectTableModel(new Table(tables)));
        // Set the document listener
        this.tfName.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                btnDone.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
                btnSqlStructure.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                btnDone.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
                btnSqlStructure.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
                btnDone.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
                btnSqlStructure.setEnabled(!tfName.getText().isEmpty() &&
                                            tableColumns.getRowCount() > 0);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new com.jm.commons.components.panel.ImagePanel();
        tfName = new com.jm.commons.components.textfield.HintJTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableColumns = new javax.swing.JTable();
        btnDone = new javax.swing.JButton();
        btnAddColumn = new javax.swing.JButton();
        btnSqlStructure = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create Table");
        setModal(true);

        mainPanel.setImage(new java.io.File("C:\\Users\\Michael\\Documents\\NetBeansProjects\\JMSql\\images\\optionslogo.png"));

        tfName.setHintText("Name...");
        tfName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                setName(evt);
            }
        });

        tableColumns.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tableColumns.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tableColumnsKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tableColumns);

        btnDone.setText("Done");
        btnDone.setEnabled(false);
        btnDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                done(evt);
            }
        });

        btnAddColumn.setText("Add Column");
        btnAddColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addColumn(evt);
            }
        });

        btnSqlStructure.setText("SQL Structure");
        btnSqlStructure.setEnabled(false);
        btnSqlStructure.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewSQLStructure(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(btnAddColumn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSqlStructure)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDone))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDone)
                    .addComponent(btnAddColumn)
                    .addComponent(btnSqlStructure))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * 
     * @param evt 
     */
    private void addColumn(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addColumn
        CreateColumn create = new CreateColumn((Frame) getParent(), this.tableColumns.getRowCount() + 1);
        create.setVisible(true);
        if (create.isDone()) {
            // Create table object
            Table table = new Table(this.tables, this.tfName.getText(), ((JMSqlObjectTableModel) this.tableColumns.getModel()).getJMSqlObject());
            // Add column to table
            Column column = create.getColumn();
            column.setEditMode(true);
            table.add(column);
            // Set the table model
            this.tableColumns.setModel(new JMSqlObjectTableModel(table));
            // Check if we can create the table
            this.btnDone.setEnabled(!this.tfName.getText().isEmpty() &&
                                        this.tableColumns.getRowCount() > 0);
            this.btnDone.setEnabled(!this.tfName.getText().isEmpty() &&
                                            this.tableColumns.getRowCount() > 0);
            this.btnSqlStructure.setEnabled(!this.tfName.getText().isEmpty() &&
                                                this.tableColumns.getRowCount() > 0);
        }
    }//GEN-LAST:event_addColumn
    
    /**
     * 
     * @param evt 
     */
    private void done(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_done
        Table table = (Table) ((JMSqlObjectTableModel) this.tableColumns.getModel()).getJMSqlObject();
        Schema schema = (Schema) ((Tables) table.getParent()).getParent();
        Definition definition = (Definition) schema.getParent();
        Database database = (Database) definition.getParent();
        try {
            this.app.newSQLEditor("SQL Table Structure " + table.getName() + ".sql", new SQLEditor((Databases) database.getParent(), definition, definition.getConnection().nativeSQL(table.createSQLQuery()), true));
            setVisible(false);
            dispose();
        } catch (SQLException sqle) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Build the tables SQL structure", sqle);
        }
    }//GEN-LAST:event_done
    
    /**
     * 
     * @param evt 
     */
    private void viewSQLStructure(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewSQLStructure
        Table table = new Table(this.tables, this.tfName.getText(), ((JMSqlObjectTableModel) this.tableColumns.getModel()).getJMSqlObject());
        Schema schema = (Schema) this.tables.getParent();
        Definition definition = (Definition) schema.getParent();
        ViewSQLStructure view = new ViewSQLStructure((Frame) getParent());
        try {
            view.setText(definition.getConnection().nativeSQL(table.createSQLQuery()));
            view.setVisible(true);
        } catch (SQLException sqle) {
            LogSystem.log(getClass(), getClass().getEnclosingMethod(), "Build the tables SQL structure", sqle);
        }
    }//GEN-LAST:event_viewSQLStructure
    
    /**
     * 
     * @param evt 
     */
    private void tableColumnsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableColumnsKeyReleased
        if (KeyEvent.VK_DELETE == evt.getKeyCode() &&
                this.tableColumns.getSelectedRows().length > 0) {
            Table table = new Table(this.tables, this.tfName.getText(), ((JMSqlObjectTableModel) this.tableColumns.getModel()).getJMSqlObject());
            for (int row : this.tableColumns.getSelectedRows()) {
                table.remove(row);
            }
            // Set the table model
            this.tableColumns.setModel(new JMSqlObjectTableModel(table));
            // Check if we can create the table
            this.btnDone.setEnabled(!this.tfName.getText().isEmpty() &&
                                        this.tableColumns.getRowCount() > 0);
            this.btnDone.setEnabled(!this.tfName.getText().isEmpty() &&
                                            this.tableColumns.getRowCount() > 0);
            this.btnSqlStructure.setEnabled(!this.tfName.getText().isEmpty() &&
                                                this.tableColumns.getRowCount() > 0);
        }
    }//GEN-LAST:event_tableColumnsKeyReleased
    
    /**
     * 
     * @param evt 
     */
    private void setName(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_setName
        if (!Character.isLetterOrDigit(evt.getKeyChar()) &&
                evt.getKeyChar()  != '_' &&
                    evt.getKeyChar() != '@' &&
                        this.tfName.getText().length() >= 25) {
            evt.consume();
        }
    }//GEN-LAST:event_setName

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddColumn;
    private javax.swing.JButton btnDone;
    private javax.swing.JButton btnSqlStructure;
    private javax.swing.JScrollPane jScrollPane1;
    private com.jm.commons.components.panel.ImagePanel mainPanel;
    private javax.swing.JTable tableColumns;
    private com.jm.commons.components.textfield.HintJTextField tfName;
    // End of variables declaration//GEN-END:variables

}
